import fs from 'fs-extra';
import path from 'path';
import { Classify, ClassifiesData, CreateClassifyRequest, UpdateClassifyRequest } from '../types/classify';
import { ApiResponse, PaginationQuery } from '../types/api';
import { PATHS } from '../config';

/**
 * 分类服务类 - 负责分类数据的文件操作
 */
export class ClassifyService {
  private classifiesFilePath: string;
  private backupPath: string;

  constructor() {
    this.classifiesFilePath = path.join(PATHS.DATA, 'classify.json');
    this.backupPath = PATHS.BACKUP;
    this.initializeDataDirectory();
  }

  /**
   * 初始化数据目录
   */
  private async initializeDataDirectory(): Promise<void> {
    try {
      // 确保数据目录存在
      await fs.ensureDir(PATHS.DATA);
      await fs.ensureDir(this.backupPath);
      
      // 如果classify.json不存在，创建空文件
      if (!(await fs.pathExists(this.classifiesFilePath))) {
        const initialData: ClassifiesData = {
          classifies: [],
          metadata: {
            version: '1.0.0',
            lastUpdated: new Date().toISOString(),
            totalCount: 0
          }
        };
        await fs.writeJson(this.classifiesFilePath, initialData, { spaces: 2 });
        console.log('Created initial classify.json file');
      }
    } catch (error) {
      console.error('Failed to initialize classifies data directory:', error);
      throw error;
    }
  }

  /**
   * 读取所有分类数据
   */
  async getAllClassifies(): Promise<Classify[]>;
  async getAllClassifies(options: {
    page?: number;
    limit?: number;
    search?: string;
    sortBy?: string;
    sortOrder?: string;
  }): Promise<{
    classifies: Classify[];
    page: number;
    limit: number;
    total: number;
    totalPages: number;
  }>;
  async getAllClassifies(options?: {
    page?: number;
    limit?: number;
    search?: string;
    sortBy?: string;
    sortOrder?: string;
  }): Promise<Classify[] | {
    classifies: Classify[];
    page: number;
    limit: number;
    total: number;
    totalPages: number;
  }> {
    try {
      const data: ClassifiesData = await fs.readJson(this.classifiesFilePath);
      let classifies = Array.isArray(data.classifies) ? data.classifies : [];
      
      // 如果没有传入选项，返回简单的分类数组
      if (!options) {
        return classifies;
      }
      
      // 应用搜索过滤
      if (options.search) {
        const searchLower = options.search.toLowerCase();
        classifies = classifies.filter(classify => 
          classify.name.toLowerCase().includes(searchLower) ||
          classify.value.toLowerCase().includes(searchLower) ||
          (classify.description || '').toLowerCase().includes(searchLower)
        );
      }
      
      // 排序
      const sortBy = options.sortBy || 'createdAt';
      const sortOrder = options.sortOrder || 'desc';
      
      classifies.sort((a, b) => {
        let aValue: any = a[sortBy as keyof Classify];
        let bValue: any = b[sortBy as keyof Classify];
        
        if (sortBy === 'createdAt' || sortBy === 'updatedAt') {
          aValue = new Date(aValue).getTime();
          bValue = new Date(bValue).getTime();
        }
        
        if (sortOrder === 'asc') {
          return aValue > bValue ? 1 : -1;
        } else {
          return aValue < bValue ? 1 : -1;
        }
      });
      
      // 分页
      const page = options.page || 1;
      const limit = options.limit || 10;
      const startIndex = (page - 1) * limit;
      const endIndex = startIndex + limit;
      
      const paginatedClassifies = classifies.slice(startIndex, endIndex);
      const totalPages = Math.ceil(classifies.length / limit);
      
      return {
        classifies: paginatedClassifies,
        page,
        limit,
        total: classifies.length,
        totalPages
      };
    } catch (error) {
      console.error('Failed to read classifies file:', error);
      return options ? {
        classifies: [],
        page: options.page || 1,
        limit: options.limit || 10,
        total: 0,
        totalPages: 0
      } : [];
    }
  }

  /**
   * 根据ID获取分类
   */
  async getClassifyById(id: string): Promise<Classify | null> {
    try {
      const classifies = await this.getAllClassifies();
      return classifies.find(classify => classify.id === id) || null;
    } catch (error) {
      console.error('Failed to get classify by ID:', error);
      return null;
    }
  }

  /**
   * 根据名称获取分类
   */
  async getClassifyByName(name: string): Promise<Classify | null> {
    try {
      const classifies = await this.getAllClassifies();
      return classifies.find(classify => classify.name === name) || null;
    } catch (error) {
      console.error('Failed to get classify by name:', error);
      return null;
    }
  }

  /**
   * 根据值获取分类
   */
  async getClassifyByValue(value: string): Promise<Classify | null> {
    try {
      const classifies = await this.getAllClassifies();
      return classifies.find(classify => classify.value === value) || null;
    } catch (error) {
      console.error('Failed to get classify by value:', error);
      return null;
    }
  }

  /**
   * 分页查询分类
   */
  async getClassifiesPaginated(query: PaginationQuery): Promise<ApiResponse<Classify[]>> {
    try {
      let classifies = await this.getAllClassifies();
      
      // 应用搜索过滤
      if (query.search) {
        const searchLower = query.search.toLowerCase();
        classifies = classifies.filter(classify => 
          classify.name.toLowerCase().includes(searchLower) ||
          classify.value.toLowerCase().includes(searchLower) ||
          (classify.description || '').toLowerCase().includes(searchLower)
        );
      }
      
      // 排序（按创建时间倒序）
      classifies.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
      
      // 分页
      const page = query.page || 1;
      const limit = query.limit || 10;
      const startIndex = (page - 1) * limit;
      const endIndex = startIndex + limit;
      
      const paginatedClassifies = classifies.slice(startIndex, endIndex);
      
      return {
        success: true,
        data: paginatedClassifies,
        total: classifies.length,
        page,
        limit
      };
    } catch (error) {
      console.error('Failed to get paginated classifies:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * 创建新分类
   */
  async createClassify(input: CreateClassifyRequest): Promise<ApiResponse<Classify>> {
    try {
      const classifies = await this.getAllClassifies();
      
      // 检查名称和值是否已存在
      const existingByName = classifies.find(classify => classify.name === input.name);
      if (existingByName) {
        return {
          success: false,
          error: 'Classify name already exists'
        };
      }
      
      const existingByValue = classifies.find(classify => classify.value === input.value);
      if (existingByValue) {
        return {
          success: false,
          error: 'Classify value already exists'
        };
      }
      
      // 生成唯一ID
      const id = this.generateId();
      const now = new Date().toISOString();
      
      const newClassify: Classify = {
        id,
        name: input.name,
        value: input.value,
        description: input.description || '',
        icon: input.icon || 'folder',
        color: input.color || '#00ccff',
        parentId: null,
        isActive: true,
        sortOrder: classifies.length + 1,
        createdAt: now,
        updatedAt: now
      };
      
      classifies.push(newClassify);
      
      // 创建备份
      await this.createBackup();
      
      // 保存到文件
      const data: ClassifiesData = {
        classifies,
        metadata: {
          version: '1.0.0',
          lastUpdated: now,
          totalCount: classifies.length
        }
      };
      await fs.writeJson(this.classifiesFilePath, data, { spaces: 2 });
      
      return {
        success: true,
        data: newClassify
      };
    } catch (error) {
      console.error('Failed to create classify:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * 更新分类
   */
  async updateClassify(id: string, input: UpdateClassifyRequest): Promise<ApiResponse<Classify>> {
    try {
      const classifies = await this.getAllClassifies();
      const classifyIndex = classifies.findIndex(classify => classify.id === id);
      
      if (classifyIndex === -1) {
        return {
          success: false,
          error: 'Classify not found'
        };
      }
      
      // 检查名称和值是否与其他分类冲突
      if (input.name) {
        const existingByName = classifies.find(classify => classify.name === input.name && classify.id !== id);
        if (existingByName) {
          return {
            success: false,
            error: 'Classify name already exists'
          };
        }
      }
      
      if (input.value) {
        const existingByValue = classifies.find(classify => classify.value === input.value && classify.id !== id);
        if (existingByValue) {
          return {
            success: false,
            error: 'Classify value already exists'
          };
        }
      }
      
      // 创建备份
      await this.createBackup();
      
      // 更新分类
      classifies[classifyIndex] = {
        ...classifies[classifyIndex],
        ...input,
        updatedAt: new Date().toISOString()
      };
      
      // 保存到文件
      const data: ClassifiesData = {
        classifies,
        metadata: {
          version: '1.0.0',
          lastUpdated: new Date().toISOString(),
          totalCount: classifies.length
        }
      };
      await fs.writeJson(this.classifiesFilePath, data, { spaces: 2 });
      
      return {
        success: true,
        data: classifies[classifyIndex]
      };
    } catch (error) {
      console.error('Failed to update classify:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * 删除分类
   */
  async deleteClassify(id: string): Promise<ApiResponse<Classify>> {
    try {
      const classifies = await this.getAllClassifies();
      const classifyIndex = classifies.findIndex(classify => classify.id === id);
      
      if (classifyIndex === -1) {
        return {
          success: false,
          error: 'Classify not found'
        };
      }
      
      // 检查是否为默认分类（可选的保护逻辑）
      const classify = classifies[classifyIndex];
      if (classify.value === 'default' || classify.value === 'general') {
        return {
          success: false,
          error: 'Cannot delete default classify'
        };
      }
      
      // 创建备份
      await this.createBackup();
      
      // 删除分类
      const deletedClassify = classifies.splice(classifyIndex, 1)[0];
      
      // 保存到文件
      const data: ClassifiesData = {
        classifies,
        metadata: {
          version: '1.0.0',
          lastUpdated: new Date().toISOString(),
          totalCount: classifies.length
        }
      };
      await fs.writeJson(this.classifiesFilePath, data, { spaces: 2 });
      
      return {
        success: true,
        data: deletedClassify
      };
    } catch (error) {
      console.error('Failed to delete classify:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }

  /**
   * 创建数据备份
   */
  private async createBackup(): Promise<void> {
    try {
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      const backupFileName = `classifies-backup-${timestamp}.json`;
      const backupFilePath = path.join(this.backupPath, backupFileName);
      
      if (await fs.pathExists(this.classifiesFilePath)) {
        await fs.copy(this.classifiesFilePath, backupFilePath);
        
        // 清理旧备份（保留最近10个）
        await this.cleanupOldBackups();
      }
    } catch (error) {
      console.error('Failed to create classifies backup:', error);
    }
  }

  /**
   * 清理旧备份文件
   */
  private async cleanupOldBackups(): Promise<void> {
    try {
      const backupFiles = await fs.readdir(this.backupPath);
      const classifyBackups = backupFiles
        .filter((file: string) => file.startsWith('classifies-backup-') && file.endsWith('.json'))
        .sort()
        .reverse(); // 最新的在前
      
      // 保留最近10个备份
      const filesToDelete = classifyBackups.slice(10);
      
      for (const file of filesToDelete) {
        await fs.remove(path.join(this.backupPath, file));
      }
    } catch (error) {
      console.error('Failed to cleanup old classify backups:', error);
    }
  }

  /**
   * 生成唯一ID
   */
  private generateId(): string {
    const { v4: uuidv4 } = require('uuid');
    return uuidv4();
  }

  /**
   * 批量删除分类
   */
  async batchDeleteClassifies(ids: string[]): Promise<number> {
    try {
      const classifies = await this.getAllClassifies();
      let deletedCount = 0;
      
      // 创建备份
      await this.createBackup();
      
      // 过滤掉要删除的分类（保护默认分类）
      const remainingClassifies = classifies.filter(classify => {
        if (ids.includes(classify.id)) {
          // 检查是否为默认分类
          if (classify.value === 'default' || classify.value === 'general') {
            return true; // 保留默认分类
          }
          deletedCount++;
          return false;
        }
        return true;
      });
      
      // 保存到文件
      const data: ClassifiesData = {
        classifies: remainingClassifies,
        metadata: {
          version: '1.0.0',
          lastUpdated: new Date().toISOString(),
          totalCount: remainingClassifies.length
        }
      };
      await fs.writeJson(this.classifiesFilePath, data, { spaces: 2 });
      
      return deletedCount;
    } catch (error) {
      console.error('Failed to batch delete classifies:', error);
      throw error;
    }
  }

  /**
   * 获取分类统计信息
   */
  async getClassifyStats(): Promise<{ totalCount: number; lastUpdated: string }> {
    try {
      const classifies = await this.getAllClassifies();
      return {
        totalCount: classifies.length,
        lastUpdated: new Date().toISOString()
      };
    } catch (error) {
      console.error('Failed to get classify stats:', error);
      throw error;
    }
  }

  /**
   * 导出分类数据
   */
  async exportClassifies(): Promise<Classify[]> {
    return await this.getAllClassifies();
  }

  /**
   * 导入分类数据
   */
  async importClassifies(classifies: Classify[]): Promise<ApiResponse<{ count: number }>> {
    try {
      // 验证数据格式
      if (!Array.isArray(classifies)) {
        return {
          success: false,
          error: 'Invalid data format: expected array'
        };
      }
      
      // 创建备份
      await this.createBackup();
      
      // 保存导入的数据
      const data: ClassifiesData = {
        classifies,
        metadata: {
          version: '1.0.0',
          lastUpdated: new Date().toISOString(),
          totalCount: classifies.length
        }
      };
      await fs.writeJson(this.classifiesFilePath, data, { spaces: 2 });
      
      return {
        success: true,
        data: { count: classifies.length }
      };
    } catch (error) {
      console.error('Failed to import classifies:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }
}

// 导出单例实例
export const classifyService = new ClassifyService();